package com.leetcode.contest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;

/**
 * @author `RKC`
 * @date 2021/10/31 11:35
 */
public class LC5900蜡烛之间的盘子 {

    public static int[] platesBetweenCandles(String s, int[][] queries) {
        List<Integer> answer = new ArrayList<>(queries.length);
        //前缀和，记录到达 | 为止，目前一共有多少个合法的 *
        TreeMap<Integer, Integer> prefixSumMap = new TreeMap<>();
        boolean startFlag = false;
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '|') {
                startFlag = true;
                prefixSumMap.put(i, sum);
                continue;
            }
            if (s.charAt(i) == '*' && startFlag) sum++;
        }
        for (int[] query : queries) {
            Integer startKey = query[0], endKey = query[1];
            //在map中找到比开始位置大的key，比结束位置小的key
            if (!prefixSumMap.containsKey(startKey)) startKey = prefixSumMap.higherKey(startKey);
            if (!prefixSumMap.containsKey(endKey)) endKey = prefixSumMap.lowerKey(endKey);

            if (startKey != null && endKey != null && endKey >= startKey) {
                answer.add(prefixSumMap.get(endKey) - prefixSumMap.get(startKey));
            } else {
                answer.add(0);
            }
        }
        return answer.stream().mapToInt(val -> val).toArray();
    }

    public static void main(String[] args) {
//        String s = "**|**|***|";
//        int[][] queries = {{2, 5}, {5, 9}};
        String s = "***|**|*****|**||**|*";
        int[][] queries = {{1, 17}, {4, 5}, {14, 17}, {5, 11}, {15, 16}};
        System.out.println(Arrays.toString(platesBetweenCandles(s, queries)));
    }
}
